package org.moda.dsl.source.loader;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * @ClassName: LoaderType
 * @Description: 加载器类型枚举
 * @Author: xuanyang
 * @Date: 2024-11-02 19:00
 * @Version: 1.0
 **/
public enum LoaderType {
    HTTP_LOADER(
        url -> Stream.of("http://", "https://").anyMatch(url::startsWith),
        HttpLoader::new
    ),

    FILE_LOADER(
        path -> !Stream.of("^[a-zA-Z]:[/\\\\].*", "^(/[^/]*)+/?$").anyMatch(path::matches),
        LocalFileLoader::new
    );
    public final Function<String, Boolean> loaderTypeF;
    public final Function<String, Loader> loaderInstanceF;

    LoaderType(Function<String, Boolean> loaderTypeF, Function<String, Loader> loaderInstanceF) {
        this.loaderTypeF = loaderTypeF;
        this.loaderInstanceF = loaderInstanceF;
    }

    public static Optional<LoaderType> maybeLoaderTypeByUri(String uri) {
        return Arrays.stream(values())
            .filter(loaderType -> loaderType.loaderTypeF.apply(uri))
            .findFirst();
    }

    public static Optional<Loader> maybeLoaderByUri(String uri) {
        return maybeLoaderTypeByUri(uri)
            .map(loaderType -> loaderType.loaderInstanceF.apply(uri));
    }
}
